package net.oaktoncc;

import gnu.io.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashSet;

/**
 * TODO: Javadoc
 *
 * @author aeagle
 */
public class TestSerial {

    public static void main(String[] args) {

        for (CommPortIdentifier port : getAvailableSerialPorts()) {
            // TODO: choose the right port, with help from the user
            try {
                System.out.println("Found port " + port.getName());

                    connect(port);
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (UnsupportedCommOperationException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (PortInUseException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }


    }

    private static void connect(CommPortIdentifier portIdentifier) throws IOException, UnsupportedCommOperationException, PortInUseException {
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open("AppName",2000);

            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(19200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();

                byte response;
                // Toggle real-time mode off
                out.write(0xFC);
                response = (byte)in.read();
                System.out.println("Device sent byte " + response);

                out.write("TOG".getBytes());
                response = (byte)in.read();
                System.out.println("Device sent byte " + response);

                out.write("OFF".getBytes());
                response = (byte)in.read();
                System.out.println("Device sent byte " + response);

                out.write(0xFC);
                response = (byte)in.read();
                System.out.println("ACK " + response);

                out.write("DNL".getBytes());
                response = (byte)in.read();
                System.out.println("DNL1 " + response);

                out.write("DNL".getBytes());
                response = (byte)in.read();
                System.out.println("DNL2 " + response);

                int lmt = 16;
                for (int count = 0; count < lmt; count++) {
                    int i = in.read();
                    System.out.println("unit info " + i);
                }

                out.write(0xFC);
                lmt=2;
                for (int count = 0; count < lmt; count++) {
                    int i = in.read();
                    System.out.println("storage interval " + i);
                }

                out.write(0xFC);
                lmt=3;
                for (int count = 0; count < lmt; count++) {
                    int i = in.read();
                    System.out.println("pointer " + i);
                }

                out.write(0xFC);
                int lastchar=0;
                for (int i = in.read(); i != -1; i = in.read()) {
                    if (i==254 && lastchar==254) {
                        break;
                    }
                    System.out.println("data record " + i);
                    lastchar = i;
                }

                out.write(0xFC);
                response = (byte)in.read();
                System.out.println("checksum " + response);

                out.write(0xFC);
                out.write("END".getBytes());
                
                commPort.close();
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    /**
     * @return    A HashSet containing the CommPortIdentifier for all serial ports that are not currently being used.
     */
    public static HashSet<CommPortIdentifier> getAvailableSerialPorts() {
        HashSet<CommPortIdentifier> h = new HashSet<CommPortIdentifier>();
        Enumeration thePorts = CommPortIdentifier.getPortIdentifiers();
        while (thePorts.hasMoreElements()) {
            CommPortIdentifier com = (CommPortIdentifier) thePorts.nextElement();
            if (com.getName().equals("/dev/cu.SLAB_USBtoUART"))
                switch (com.getPortType()) {
                case CommPortIdentifier.PORT_SERIAL:
                    try {
                        CommPort thePort = com.open("CommUtil", 50);
                        thePort.close();
                        h.add(com);
                    } catch (PortInUseException e) {
                        System.out.println("Port " +  com.getName() +  ", is in use.");
                    } catch (Exception e) {
                        System.err.println("Failed to open port "  + com.getName());
                        e.printStackTrace();
                    }
                }
        }
        return h;
    }
}
